<template>
  <div class="sampling-board">
    <!-- 顶部导航 -->
    <van-nav-bar
      title="取样任务看板"
      left-text="返回"
      left-arrow
      @click-left="$router.go(-1)"
      fixed
      placeholder
    >
      <template #right>
        <van-icon name="search" size="18" @click="showSearch = true" />
      </template>
    </van-nav-bar>

    <!-- 搜索框 -->
    <van-search
      v-model="searchValue"
      v-show="showSearch"
      placeholder="搜索冷库名称或地址"
      @search="onSearch"
      @cancel="showSearch = false"
      @blur="showSearch = false"
    />

    <!-- 统计卡片 -->
    <div class="stats-container">
      <div class="stat-card">
        <div class="stat-value">{{ totalTasks }}</div>
        <div class="stat-label">总任务数</div>
      </div>
      <div class="stat-card">
        <div class="stat-value">{{ pendingTasks }}</div>
        <div class="stat-label">待取样</div>
      </div>
      <div class="stat-card">
        <div class="stat-value">{{ inProgressTasks }}</div>
        <div class="stat-label">进行中</div>
      </div>
    </div>

    <!-- 分组标签 -->
    <div class="groups-tabs">
      <van-tabs v-model:active="activeTab" @change="changeTab" shrink swipeable>
        <van-tab v-for="(group, index) in filteredGroups" :title="group.name" :key="index" />
      </van-tabs>
    </div>

    <!-- 分组内容 -->
    <div class="group-content">
      <!-- 空状态 -->
      <div v-if="activeStorages.length === 0" class="empty-status">
        <van-empty image="search" description="没有找到符合条件的冷库">
          <van-button round type="primary" class="reset-btn" @click="resetSearch">
            重置筛选条件
          </van-button>
        </van-empty>
      </div>

      <!-- 冷库列表 -->
      <div v-else>
        <van-cell title="冷库分组统计" class="group-header">
          <template #value>
            <span class="storage-count">{{ activeStorages.length }}个冷库</span>
          </template>
        </van-cell>

        <div v-for="storage in activeStorages" :key="storage.id" class="storage-card">
          <van-swipe-cell>
            <!-- 冷库卡片内容 -->
            <div class="storage-content">
              <!-- 顶部信息 -->
              <div class="storage-header">
                <div class="storage-name">
                  <van-tag type="primary" size="medium">
                    {{ storage.group }}
                  </van-tag>
                  <h3>{{ storage.name }}</h3>
                </div>
                <div class="task-count">
                  <span class="count-badge">{{ storage.tasksCount }}</span>
                  <span>个任务</span>
                </div>
              </div>

              <!-- 冷库信息 -->
              <div class="storage-info">
                <div class="address">
                  <van-icon name="location" size="14px" color="#1989fa" />
                  <span>{{ storage.address }}</span>
                </div>
                <div class="coordinates">
                  <van-icon name="point-gift" size="14px" color="#1989fa" />
                  <span>纬度: {{ storage.latitude }}, 经度: {{ storage.longitude }}</span>
                </div>
                <div class="capacity">
                  <van-icon name="discount" size="14px" color="#1989fa" />
                  <span>容量: {{ storage.capacity }}m³</span>
                </div>
              </div>
              <!-- 操作按钮 -->
              <div class="action-buttons">
                <van-button
                  round
                  icon="location"
                  size="small"
                  type="primary"
                  plain
                  @click="showMap(storage)"
                >
                  查看位置
                </van-button>
                <van-button round size="small" type="primary" @click="viewStorageTasks(storage.id)">
                  查看任务({{ storage.tasksCount }})
                </van-button>
              </div>
            </div>

            <!-- 右滑操作 -->
            <!-- <template #right>
              <van-button
                square
                type="danger"
                text="删除"
                class="delete-button"
                @click="deleteStorage(storage.id)"
              />
            </template> -->
          </van-swipe-cell>
        </div>
      </div>
    </div>

    <!-- 地图弹窗 -->
    <van-popup v-model:show="showMapPopup" position="bottom" round :style="{ height: '80%' }">
      <div class="map-container">
        <div class="map-header">
          <h3>{{ selectedStorage?.name }}</h3>
          <van-icon name="cross" size="20" @click="showMapPopup = false" />
        </div>

        <div class="mock-map">
          <div class="map-image">
            <img src="../assets/map-placeholder.jpg" alt="地图位置" />
            <div class="map-marker">
              <van-icon name="location" size="24" color="#f44336" />
            </div>
          </div>
          <div class="map-info">
            <p><strong>地址:</strong> {{ selectedStorage?.address }}</p>
            <p>
              <strong>坐标:</strong> 纬度 {{ selectedStorage?.latitude }}, 经度
              {{ selectedStorage?.longitude }}
            </p>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
// import { Toast, Dialog } from 'vant'
import type { ColdStorage, ColdStorageGroup } from '../types/task'

export default defineComponent({
  name: 'SamplingBoard',
  setup() {
    const router = useRouter()

    // 搜索相关状态
    const searchValue = ref('')
    const showSearch = ref(false)

    // 分组相关状态
    const activeTab = ref(0)
    const groups = ref<ColdStorageGroup[]>([])
    const showMapPopup = ref(false)
    const selectedStorage = ref<ColdStorage | null>(null)

    // 模拟冷库数据
    const coldStorages = ref<ColdStorage[]>([
      {
        id: 'cs1',
        name: '华南冷链中心',
        group: '华南区',
        address: '广东省广州市黄埔区科学城开源大道188号',
        latitude: 23.1832,
        longitude: 113.511,
        capacity: 12000,
        currentUsage: 9500,
        tasksCount: 8,
      },
      {
        id: 'cs2',
        name: '华东冷藏基地',
        group: '华东区',
        address: '上海市浦东新区张江高科园区创新路99号',
        latitude: 31.2134,
        longitude: 121.539,
        capacity: 18000,
        currentUsage: 11500,
        tasksCount: 12,
      },
      {
        id: 'cs3',
        name: '华北冷藏中心',
        group: '华北区',
        address: '北京市海淀区上地科技园区8号',
        latitude: 39.9931,
        longitude: 116.321,
        capacity: 9000,
        currentUsage: 7000,
        tasksCount: 5,
      },
      {
        id: 'cs4',
        name: '西南冷冻仓库',
        group: '西南区',
        address: '四川省成都市高新区天府软件园C区8号楼',
        latitude: 30.5482,
        longitude: 104.067,
        capacity: 15000,
        currentUsage: 11000,
        tasksCount: 15,
      },
      {
        id: 'cs5',
        name: '华南冷冻基地',
        group: '华南区',
        address: '广东省深圳市南山区科技园北区6号楼',
        latitude: 22.5521,
        longitude: 113.949,
        capacity: 11000,
        currentUsage: 8500,
        tasksCount: 7,
      },
      {
        id: 'cs6',
        name: '华东冷链枢纽',
        group: '华东区',
        address: '浙江省杭州市余杭区未来科技城88号',
        latitude: 30.2898,
        longitude: 120.006,
        capacity: 22000,
        currentUsage: 14500,
        tasksCount: 18,
      },
    ])

    // 分组统计数据
    const generateGroups = () => {
      const groupsMap: Record<string, ColdStorage[]> = {}

      coldStorages.value.forEach((storage) => {
        if (!groupsMap[storage.group]) {
          groupsMap[storage.group] = []
        }
        groupsMap[storage.group].push(storage)
      })

      groups.value = Object.keys(groupsMap).map((groupName) => ({
        name: groupName,
        count: groupsMap[groupName].length,
        storages: groupsMap[groupName],
      }))

      // 添加"全部"分组
      groups.value.unshift({
        name: '全部',
        count: coldStorages.value.length,
        storages: coldStorages.value,
      })
    }

    // 查看地图
    const showMap = (storage: ColdStorage) => {
      selectedStorage.value = storage
      showMapPopup.value = true
    }

    // 查看任务
    const viewStorageTasks = (storageId: string) => {
      router.push({ name: 'taskDetail', query: { id: storageId } })
    }

    // 删除冷库
    // const deleteStorage = (id: string) => {
    //   Dialog({
    //     title: '删除冷库',
    //     message: '确定要删除这个冷库吗？此操作不可撤销。',
    //   }).then(() => {
    //     const index = coldStorages.value.findIndex((s) => s.id === id)
    //     if (index !== -1) {
    //       coldStorages.value.splice(index, 1)
    //       Toast('冷库已删除')
    //       generateGroups()
    //     }
    //   })
    // }

    // 搜索功能
    const onSearch = () => {
      generateGroups()
      showSearch.value = false
    }

    // 重置搜索
    const resetSearch = () => {
      searchValue.value = ''
      generateGroups()
    }

    // 改变标签
    const changeTab = () => {
      // 标签切换时自动滚动到顶部
      window.scrollTo({ top: 0, behavior: 'smooth' })
    }

    // 计算属性
    const filteredGroups = computed(() => {
      if (!searchValue.value) return groups.value

      return groups.value
        .map((group) => {
          const filtered = group.storages.filter((storage) => {
            const search = searchValue.value.toLowerCase()
            return (
              storage.name.toLowerCase().includes(search) ||
              storage.address.toLowerCase().includes(search)
            )
          })

          return {
            name: group.name,
            count: filtered.length,
            storages: filtered,
          }
        })
        .filter((group) => group.count > 0)
    })

    const activeStorages = computed(() => {
      if (!filteredGroups.value[activeTab.value]) return []
      return filteredGroups.value[activeTab.value].storages
    })

    // 任务统计
    const totalTasks = computed(() => {
      return coldStorages.value.reduce((sum, storage) => sum + storage.tasksCount, 0)
    })

    const pendingTasks = computed(() => {
      // 模拟数据，实际情况应基于任务状态
      return Math.floor(totalTasks.value * 0.35)
    })

    const inProgressTasks = computed(() => {
      // 模拟数据
      return Math.floor(totalTasks.value * 0.25)
    })

    // 生命周期
    onMounted(() => {
      generateGroups()
    })

    return {
      searchValue,
      showSearch,
      activeTab,
      groups,
      filteredGroups,
      activeStorages,
      showMapPopup,
      selectedStorage,
      totalTasks,
      pendingTasks,
      inProgressTasks,
      showMap,
      viewStorageTasks,
      // deleteStorage,
      onSearch,
      resetSearch,
      changeTab,
    }
  },
})
</script>

<style lang="scss" scoped>
.sampling-board {
  padding-bottom: 60px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .stats-container {
    display: flex;
    justify-content: space-around;
    padding: 16px;
    background: white;
    margin-bottom: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    .stat-card {
      text-align: center;

      .stat-value {
        font-size: 24px;
        font-weight: bold;
        color: #1989fa;
      }

      .stat-label {
        font-size: 13px;
        color: #969799;
      }
    }
  }

  .groups-tabs {
    background: white;
    padding: 0 16px;
    margin-bottom: 8px;
    position: sticky;
    top: 46px; // 导航栏高度
    z-index: 99;

    :deep(.van-tabs__line) {
      background: #1989fa;
    }
  }

  .group-content {
    padding: 0 12px;

    .group-header {
      background-color: #f0f7ff;
      border-radius: 8px 8px 0 0;
      margin-top: 12px;
      font-weight: bold;

      .storage-count {
        color: #1989fa;
        font-weight: bold;
      }
    }

    .storage-card {
      margin-bottom: 12px;
      border-radius: 8px;
      overflow: hidden;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

      .storage-content {
        background: white;
        padding: 16px;
        border: none;

        .storage-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 12px;
          padding-bottom: 12px;
          border-bottom: 1px solid #f7f8fa;

          .storage-name {
            display: flex;
            align-items: center;

            .van-tag {
              margin-right: 8px;
            }

            h3 {
              margin: 0;
              font-size: 17px;
              color: #333;
            }
          }

          .task-count {
            color: #666;
            font-size: 14px;

            .count-badge {
              display: inline-block;
              min-width: 24px;
              height: 24px;
              background: #1989fa;
              color: white;
              border-radius: 12px;
              text-align: center;
              line-height: 24px;
              font-weight: bold;
              margin-right: 4px;
            }
          }
        }

        .storage-info {
          > div {
            display: flex;
            align-items: flex-start;
            margin-bottom: 8px;
            font-size: 13px;
            color: #666;

            .van-icon {
              flex-shrink: 0;
              margin-top: 2px;
              margin-right: 8px;
            }
          }
        }

        .progress-section {
          margin: 16px 0;

          .progress-labels {
            display: flex;
            justify-content: space-between;
            margin-top: 4px;
            color: #969799;
            font-size: 12px;
          }
        }

        .action-buttons {
          display: flex;
          justify-content: space-between;

          .van-button {
            flex: 1;
            margin: 0 5px;
          }
        }
      }

      .delete-button {
        height: 100%;
      }
    }

    .empty-status {
      margin-top: 60px;

      .reset-btn {
        margin-top: 16px;
      }
    }
  }

  .map-container {
    padding: 16px;
    height: 100%;
    display: flex;
    flex-direction: column;

    .map-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      h3 {
        margin: 0;
        font-size: 18px;
        color: #333;
      }
    }

    .mock-map {
      flex: 1;
      display: flex;
      flex-direction: column;
      background-color: #f9f9f9;
      border-radius: 8px;
      overflow: hidden;

      .map-image {
        position: relative;
        height: 300px;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }

        .map-marker {
          position: absolute;
          top: 45%;
          left: 55%;
          transform: translate(-50%, -100%);
          font-size: 0;
        }
      }

      .map-info {
        padding: 16px;
        background: white;

        p {
          margin: 8px 0;
          font-size: 14px;
          color: #333;
        }
      }
    }
  }
}
</style>
